<template>
  <div class="replenish-plan-page">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="card-content">
            <div class="card-icon pending">
              <el-icon size="24"><Clock /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stats.pending }}</div>
              <div class="card-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="card-content">
            <div class="card-icon approved">
              <el-icon size="24"><CircleCheck /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stats.approved }}</div>
              <div class="card-label">已审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="card-content">
            <div class="card-icon executing">
              <el-icon size="24"><Operation /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stats.executing }}</div>
              <div class="card-label">执行中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="card-content">
            <div class="card-icon completed">
              <el-icon size="24"><Select /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stats.completed }}</div>
              <div class="card-label">已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 补货计划管理 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <div class="page-header">
          <h3>补货计划管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog">
              <el-icon><Plus /></el-icon>
              创建补货计划
            </el-button>
            <el-button type="success" @click="handleAutoGenerate">
              <el-icon><MagicStick /></el-icon>
              智能生成
            </el-button>
            <el-button @click="handleExport">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选区域 -->
      <div class="filter-area">
        <el-form :model="filterForm" inline>
          <el-form-item label="补货单号">
            <el-input v-model="filterForm.orderNo" placeholder="请输入单号" clearable style="width: 150px" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="待审核" value="pending" />
              <el-option label="已审核" value="approved" />
              <el-option label="执行中" value="executing" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="filterForm.warehouse" placeholder="请选择仓库" clearable style="width: 120px">
              <el-option label="主仓库" value="main" />
              <el-option label="分仓库A" value="branchA" />
              <el-option label="分仓库B" value="branchB" />
            </el-select>
          </el-form-item>
          <el-form-item label="紧急度">
            <el-select v-model="filterForm.urgency" placeholder="请选择紧急度" clearable style="width: 120px">
              <el-option label="紧急" value="urgent" />
              <el-option label="重要" value="important" />
              <el-option label="普通" value="normal" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 补货计划列表 -->
      <el-table
        :data="planList"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="补货单号" width="150">
          <template #default="{ row }">
            <el-link type="primary" @click="viewDetail(row)">{{ row.orderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse" label="仓库" width="100" />
        <el-table-column prop="productCount" label="商品数量" width="100" align="center">
          <template #default="{ row }">
            {{ row.products.length }} 种
          </template>
        </el-table-column>
        <el-table-column prop="totalQty" label="总数量" width="100" align="right">
          <template #default="{ row }">
            {{ row.products.reduce((sum, p) => sum + p.qty, 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="预估金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="urgency" label="紧急度" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getUrgencyType(row.urgency)">{{ row.urgency }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="expectedDate" label="预计到货" width="120" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status === 'pending'" link type="success" @click="handleApprove(row)">
              <el-icon><CircleCheck /></el-icon>
              审核
            </el-button>
            <el-button v-if="row.status === 'approved'" link type="primary" @click="handleExecute(row)">
              <el-icon><Operation /></el-icon>
              执行
            </el-button>
            <el-button v-if="row.status === 'executing'" link type="warning" @click="handleComplete(row)">
              <el-icon><Select /></el-icon>
              完成
            </el-button>
            <el-button link type="primary" @click="viewDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button v-if="['pending', 'approved'].includes(row.status)" link type="danger" @click="handleCancel(row)">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建补货计划对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建补货计划" width="1000px">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouse">
              <el-select v-model="createForm.warehouse" placeholder="请选择仓库" style="width: 100%">
                <el-option label="主仓库" value="main" />
                <el-option label="分仓库A" value="branchA" />
                <el-option label="分仓库B" value="branchB" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急度" prop="urgency">
              <el-select v-model="createForm.urgency" placeholder="请选择紧急度" style="width: 100%">
                <el-option label="紧急" value="urgent" />
                <el-option label="重要" value="important" />
                <el-option label="普通" value="normal" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="预计到货日期" prop="expectedDate">
              <el-date-picker
                v-model="createForm.expectedDate"
                type="date"
                placeholder="请选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="补货商品">
          <el-button type="primary" size="small" @click="showProductSelector">
            <el-icon><Plus /></el-icon>
            添加商品
          </el-button>
        </el-form-item>

        <el-table :data="createForm.products" border style="margin-bottom: 20px">
          <el-table-column prop="code" label="商品编码" width="120" />
          <el-table-column prop="name" label="商品名称" min-width="150" />
          <el-table-column prop="currentStock" label="当前库存" width="100" align="right" />
          <el-table-column prop="safetyStock" label="安全库存" width="100" align="right" />
          <el-table-column prop="suggestQty" label="建议数量" width="100" align="right" />
          <el-table-column label="补货数量" width="150">
            <template #default="{ row }">
              <el-input-number
                v-model="row.qty"
                :min="1"
                :step="10"
                size="small"
                style="width: 130px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="采购单价" width="100" align="right">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120" align="right">
            <template #default="{ row }">
              ¥{{ (row.qty * row.price).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button link type="danger" @click="removeProduct($index)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="备注">
          <el-input
            v-model="createForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="补货计划详情" width="1000px">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="补货单号">{{ currentDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ currentDetail.warehouse }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentDetail.status)">
            {{ getStatusName(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="紧急度">
          <el-tag :type="getUrgencyType(currentDetail.urgency)">
            {{ currentDetail.urgency }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentDetail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ currentDetail.creator }}</el-descriptions-item>
        <el-descriptions-item label="预计到货">{{ currentDetail.expectedDate }}</el-descriptions-item>
        <el-descriptions-item label="总金额">
          ¥{{ currentDetail.totalAmount?.toLocaleString() }}
        </el-descriptions-item>
        <el-descriptions-item label="审核人">{{ currentDetail.approver || '-' }}</el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 20px">
        <h4>补货商品明细</h4>
        <el-table :data="currentDetail.products" border>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="code" label="商品编码" width="120" />
          <el-table-column prop="name" label="商品名称" min-width="150" />
          <el-table-column prop="currentStock" label="当前库存" width="100" align="right" />
          <el-table-column prop="safetyStock" label="安全库存" width="100" align="right" />
          <el-table-column prop="qty" label="补货数量" width="100" align="right" />
          <el-table-column prop="price" label="采购单价" width="100" align="right">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120" align="right">
            <template #default="{ row }">
              ¥{{ (row.qty * row.price).toLocaleString() }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="currentDetail.remark" style="margin-top: 20px">
        <h4>备注信息</h4>
        <div style="padding: 10px; background: #f5f7fa; border-radius: 4px">
          {{ currentDetail.remark }}
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 商品选择器对话框 -->
    <el-dialog v-model="productSelectorVisible" title="选择商品" width="800px">
      <el-input
        v-model="productSearchText"
        placeholder="搜索商品名称或编码"
        clearable
        style="margin-bottom: 15px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-table
        :data="availableProducts"
        @selection-change="handleProductSelection"
        max-height="400"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="currentStock" label="当前库存" width="100" align="right" />
        <el-table-column prop="safetyStock" label="安全库存" width="100" align="right" />
        <el-table-column prop="suggestQty" label="建议数量" width="100" align="right" />
        <el-table-column prop="price" label="采购单价" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="productSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 统计数据
const stats = reactive({
  pending: 8,
  approved: 12,
  executing: 5,
  completed: 156
})

// 筛选表单
const filterForm = reactive({
  orderNo: '',
  status: '',
  warehouse: '',
  urgency: '',
  dateRange: []
})

// 表格数据
const loading = ref(false)
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const planList = ref([
  {
    id: 1,
    orderNo: 'RO202401150001',
    warehouse: '主仓库',
    products: [
      { code: 'P001', name: 'iPhone 14 Pro Max 256GB', currentStock: 15, safetyStock: 30, qty: 85, suggestQty: 85, price: 9000 },
      { code: 'P002', name: '华为 Mate 50 Pro', currentStock: 22, safetyStock: 25, qty: 58, suggestQty: 58, price: 5500 }
    ],
    totalAmount: 1084000,
    urgency: '紧急',
    status: 'pending',
    createTime: '2024-01-15 10:30:00',
    creator: '张三',
    expectedDate: '2024-01-22',
    approver: null,
    remark: '手机类商品库存严重不足，需紧急补货'
  },
  {
    id: 2,
    orderNo: 'RO202401140001',
    warehouse: '分仓库A',
    products: [
      { code: 'P003', name: '小米13 Ultra', currentStock: 8, safetyStock: 20, qty: 70, suggestQty: 70, price: 4500 },
    ],
    totalAmount: 315000,
    urgency: '重要',
    status: 'approved',
    createTime: '2024-01-14 14:20:00',
    creator: '李四',
    expectedDate: '2024-01-20',
    approver: '王五',
    remark: null
  },
  {
    id: 3,
    orderNo: 'RO202401130001',
    warehouse: '主仓库',
    products: [
      { code: 'P004', name: 'OPPO Find X6 Pro', currentStock: 35, safetyStock: 30, qty: 35, suggestQty: 35, price: 5000 },
    ],
    totalAmount: 175000,
    urgency: '普通',
    status: 'executing',
    createTime: '2024-01-13 09:15:00',
    creator: '赵六',
    expectedDate: '2024-01-18',
    approver: '王五',
    remark: null
  },
  {
    id: 4,
    orderNo: 'RO202401120001',
    warehouse: '分仓库B',
    products: [
      { code: 'P005', name: 'vivo X90 Pro+', currentStock: 12, safetyStock: 25, qty: 65, suggestQty: 65, price: 6000 },
    ],
    totalAmount: 390000,
    urgency: '重要',
    status: 'completed',
    createTime: '2024-01-12 16:45:00',
    creator: '孙七',
    expectedDate: '2024-01-17',
    approver: '王五',
    remark: null
  }
])

total.value = planList.value.length

// 创建对话框
const createDialogVisible = ref(false)
const createFormRef = ref(null)
const createForm = reactive({
  warehouse: '',
  urgency: 'normal',
  expectedDate: '',
  products: [],
  remark: ''
})

const createRules = {
  warehouse: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  urgency: [{ required: true, message: '请选择紧急度', trigger: 'change' }],
  expectedDate: [{ required: true, message: '请选择预计到货日期', trigger: 'change' }]
}

// 详情对话框
const detailVisible = ref(false)
const currentDetail = ref({})

// 商品选择器
const productSelectorVisible = ref(false)
const productSearchText = ref('')
const selectedProducts = ref([])

const availableProducts = ref([
  { code: 'P001', name: 'iPhone 14 Pro Max 256GB', currentStock: 15, safetyStock: 30, suggestQty: 85, price: 9000 },
  { code: 'P002', name: '华为 Mate 50 Pro', currentStock: 22, safetyStock: 25, suggestQty: 58, price: 5500 },
  { code: 'P003', name: '小米13 Ultra', currentStock: 8, safetyStock: 20, suggestQty: 70, price: 4500 },
  { code: 'P004', name: 'OPPO Find X6 Pro', currentStock: 35, safetyStock: 30, suggestQty: 35, price: 5000 },
  { code: 'P005', name: 'vivo X90 Pro+', currentStock: 12, safetyStock: 25, suggestQty: 65, price: 6000 }
])

// 获取紧急度类型
const getUrgencyType = (urgency) => {
  const map = { '紧急': 'danger', '重要': 'warning', '普通': '' }
  return map[urgency] || ''
}

// 获取状态名称
const getStatusName = (status) => {
  const map = {
    pending: '待审核',
    approved: '已审核',
    executing: '执行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    approved: 'primary',
    executing: '',
    completed: 'success',
    cancelled: 'info'
  }
  return map[status] || ''
}

// 筛选
const handleFilter = () => {
  loading.value = true
  setTimeout(() => {
    ElMessage.success('查询完成')
    loading.value = false
  }, 500)
}

// 重置筛选
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = key === 'dateRange' ? [] : ''
  })
  handleFilter()
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 显示创建对话框
const showCreateDialog = () => {
  createForm.warehouse = ''
  createForm.urgency = 'normal'
  createForm.expectedDate = ''
  createForm.products = []
  createForm.remark = ''
  createDialogVisible.value = true
}

// 显示商品选择器
const showProductSelector = () => {
  productSelectorVisible.value = true
}

// 商品选择
const handleProductSelection = (rows) => {
  selectedProducts.value = rows
}

// 确认商品选择
const confirmProductSelection = () => {
  selectedProducts.value.forEach(product => {
    if (!createForm.products.find(p => p.code === product.code)) {
      createForm.products.push({
        ...product,
        qty: product.suggestQty
      })
    }
  })
  productSelectorVisible.value = false
  ElMessage.success(`已添加 ${selectedProducts.value.length} 个商品`)
}

// 移除商品
const removeProduct = (index) => {
  createForm.products.splice(index, 1)
}

// 创建
const handleCreate = () => {
  createFormRef.value.validate((valid) => {
    if (valid) {
      if (createForm.products.length === 0) {
        ElMessage.warning('请添加补货商品')
        return
      }
      ElMessage.success('补货计划创建成功')
      createDialogVisible.value = false
    }
  })
}

// 智能生成
const handleAutoGenerate = () => {
  ElMessageBox.confirm('系统将根据库存情况和补货规则自动生成补货计划，是否继续？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    ElMessage.success('已生成 3 个补货计划')
  })
}

// 查看详情
const viewDetail = (row) => {
  currentDetail.value = { ...row }
  detailVisible.value = true
}

// 审核
const handleApprove = (row) => {
  ElMessageBox.confirm(`确认审核通过补货单 ${row.orderNo} 吗？`, '提示', {
    confirmButtonText: '通过',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    row.status = 'approved'
    row.approver = '王五'
    ElMessage.success('审核通过')
  })
}

// 执行
const handleExecute = (row) => {
  ElMessageBox.confirm(`确认执行补货单 ${row.orderNo} 吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = 'executing'
    ElMessage.success('开始执行补货')
  })
}

// 完成
const handleComplete = (row) => {
  ElMessageBox.confirm(`确认补货单 ${row.orderNo} 已完成吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    row.status = 'completed'
    ElMessage.success('补货已完成')
  })
}

// 取消
const handleCancel = (row) => {
  ElMessageBox.confirm(`确认取消补货单 ${row.orderNo} 吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = 'cancelled'
    ElMessage.success('已取消补货单')
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 分页
const handleSizeChange = (size) => {
  pageSize.value = size
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}
</script>

<style scoped lang="scss">
.replenish-plan-page {
  padding: 20px;

  .stats-cards {
    margin-bottom: 20px;

    .stat-card {
      .card-content {
        display: flex;
        align-items: center;

        .card-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          &.pending {
            background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%);
            color: #fff;
          }

          &.approved {
            background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
            color: #fff;
          }

          &.executing {
            background: linear-gradient(135deg, #a29bfe 0%, #6c5ce7 100%);
            color: #fff;
          }

          &.completed {
            background: linear-gradient(135deg, #55efc4 0%, #00b894 100%);
            color: #fff;
          }
        }

        .card-info {
          flex: 1;

          .card-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
            margin-bottom: 8px;
          }

          .card-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .filter-area {
    margin-bottom: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

